<template>
  <div class="app-contanier" :class="$isMobile ? '' : 'pc-container'">
    <div class="form-content no-scrollbar">
      <!--主题-->
      <div class="content-place"></div>
      <div class="cell-item">
        <div class="label">主题</div>
        <div class="content">
          <div class="content-inner">
            <van-field
              v-model="liveForm.title"
              :maxlength="40"
              placeholder="请输入直播主题（40字以内）"
            />
          </div>
        </div>
      </div>
      <div class="cell-item">
        <div class="label">主讲人</div>
        <div class="content">
          <div class="content-inner">
            <van-field
              v-model="liveForm.speaker"
              :maxlength="20"
              placeholder="请输入直播的主讲人（20字以内）"
            />
          </div>
        </div>
      </div>
      <!--开始时间-->
      <div class="cell-item">
        <div class="label">开始</div>
        <div class="content">
          <div
            class="content-inner"
            v-if="$isMobile"
            @click="showCalendar = true"
          >
            <van-field
              v-model="liveForm.dateText"
              placeholder="请选择日期"
              readonly
            />
            <i class="sdlive icon-rili float-icon"></i>
          </div>
          <div class="content-inner date-picker" v-else>
            <el-date-picker
              v-model="liveForm.date"
              placeholder="请选择日期"
              :clearable="false"
              :editable="false"
              :disabled-date="disabledDate"
            >
            </el-date-picker>
            <i class="sdlive icon-rili float-icon"></i>
          </div>
        </div>
        <div class="time-content">
          <div class="content-inner" v-if="$isMobile" @click="showTime = true">
            <van-field
              v-model="liveForm.time"
              placeholder="请选择时间"
              readonly
            />
            <i class="sdlive icon-xiangxia float-icon"></i>
          </div>
          <div class="content-inner date-picker" v-else>
            <el-time-picker
              v-model="liveForm.elTimeDate"
              placeholder="请选择时间"
              format="HH:mm"
              :clearable="false"
              :editable="false"
            />
            <i class="sdlive icon-xiangxia float-icon"></i>
          </div>
        </div>
      </div>
      <!--时长-->
      <div class="cell-item">
        <div class="label">时长</div>
        <div class="content">
          <div
            class="content-inner"
            v-if="$isMobile"
            @click="showDuration = true"
          >
            <van-field
              v-model="liveForm.durationText"
              placeholder="请选择时长"
              readonly
            />
            <i class="sdlive icon-xiangxia float-icon"></i>
          </div>
          <div class="content-inner date-picker" v-else>
            <el-select
              v-model="liveForm.durationTime[0]"
              placeholder="请选择时长"
            >
              <el-option
                class="duration-select"
                v-for="item in TIME_COLUMNS"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
            <i class="sdlive icon-xiangxia float-icon"></i>
          </div>
        </div>
      </div>
      <!--入会密码-->
      <div class="cell-item">
        <div class="label">密码</div>
        <div class="content">
          <div
            class="content-inner"
            v-if="$isMobile"
            @click="numBoardShow = true"
          >
            <van-field
              v-model.number="liveForm.meetingPassword"
              :type="showPw ? 'number' : 'password'"
              placeholder="请输入6位数字密码"
              readonly
            />
            <i
              :class="[
                'sdlive float-icon',
                showPw ? 'icon-view' : 'icon-no-view',
              ]"
              @click.stop="showPw = !showPw"
            ></i>
          </div>
          <div class="content-inner" v-else>
            <van-field
              v-model.number="liveForm.meetingPassword"
              :type="showPw ? 'number' : 'password'"
              :maxlength="6"
              placeholder="请输入6位密码"
            />
            <i
              :class="[
                'sdlive float-icon',
                showPw ? 'icon-view' : 'icon-no-view',
              ]"
              @click.stop="showPw = !showPw"
            ></i>
          </div>
        </div>
      </div>
      <!--主持密码-->
      <div class="cell-item">
        <div class="label">主持密码</div>
        <div class="content">
          <div class="content-inner">
            <van-field
              v-model="liveForm.controlPassword"
              :maxlength="6"
              placeholder="请输入6位密码"
              readonly
            />
          </div>
        </div>
      </div>
      <!--录制-->
      <div class="cell-item">
        <div class="label">录制</div>
        <van-checkbox v-model="liveForm.autoRecording" shape="square">
          自动开启录制
        </van-checkbox>
      </div>
      <!--地点-->
      <div class="cell-item">
        <div class="label">地点</div>
        <div class="content">
          <div class="content-inner">
            <van-field
              v-model="liveForm.location"
              :maxlength="40"
              placeholder="请输入直播地点（40字以内）"
            />
          </div>
        </div>
      </div>
      <div class="content-place"></div>
      <div class="desc-item">
        <div class="label">直播简介</div>
        <div class="desc-inner">
          <van-field
            v-model="liveForm.briefIntroduction"
            rows="2"
            type="textarea"
            :maxlength="100"
            placeholder="请输入直播简介（100字以内）"
            show-word-limit
          />
        </div>
      </div>
      <div class="content-place"></div>
      <!--参会人员-->
      <div class="join-users">
        <div class="cell-item" @click="chooseUser">
          <div class="label">参与人</div>
          <div class="content join-number">{{ selectedUsers.length }} 人</div>
          <van-icon name="arrow" size="16px" color="#666" />
        </div>
        <ul class="users-list">
          <template v-if="selectedUsers.length">
            <li
              v-for="(item, index) in selectedUsers"
              :key="item.id"
              class="user"
            >
              {{ item.name }}
              <van-icon
                @click="delUser(index)"
                class="del-icon"
                name="clear"
                color="#F56C6C"
              />
            </li>
          </template>
          <li class="no-users" v-else>未选择参与人员</li>
        </ul>
      </div>
    </div>
    <div class="foot-btns">
      <van-button type="primary" block @click="submitForm">{{
        isEdit ? "保存" : "预定"
      }}</van-button>
    </div>
  </div>

  <!--密码的数字键盘-->
  <van-number-keyboard
    v-model="liveForm.meetingPassword"
    :show="numBoardShow"
    :maxlength="6"
    @blur="numBoardShow = false"
  />

  <!--日历-->
  <van-calendar
    :default-date="liveForm.date"
    v-model:show="showCalendar"
    @confirm="onDateConfirm"
  />

  <!--时分选择-->
  <van-popup v-model:show="showTime" position="bottom">
    <van-time-picker
      v-model="liveForm.pickerTime"
      title="选择时间"
      @confirm="onTimeConfirm"
      @cancel="showTime = false"
    />
  </van-popup>

  <!--直播时长-->
  <van-popup v-model:show="showDuration" position="bottom">
    <van-picker
      title="选择时长"
      v-model="liveForm.durationTime"
      :columns="TIME_COLUMNS"
      @confirm="onDurationConfirm"
      @cancel="showDuration = false"
    />
  </van-popup>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { showLoadingToast } from 'vant'

import { useAuthStore } from '@/store/auth'

import { TIME_COLUMNS, TIME_COLOBJ } from '@/source/index'

import { VantMessage } from '@/utils/vant-utils'
import { getRandomInt, WEB_HREF } from '@/utils/index'

import { saveLive, getInfo } from '@/api/live'
import { sendMsgCard } from '@/api/index'

import { sm2Encrypt, sm2Decrypt } from '@/utils/sm2'

import { wxContacts } from '@/utils/wx'

const $route = useRoute()
const $router = useRouter()
const authStore = useAuthStore()

const liveForm = reactive({
  id: '',
  title: '', // 直播主题
  speaker: '', // 主讲人
  date: '',
  dateText: '',
  time: '', // 直播时间
  pickerTime: [], // 初始化设置一下
  elTimeDate: '', // pc端el的时间
  durationTime: [30], // 时长
  durationText: '30分钟', // 时长
  meetingPassword: '', // 直播密码
  controlPassword: '', // 主持密码
  autoRecording: false, // 是否开启录制
  location: '', // 直播地点
  briefIntroduction: '' // 简介
})

const showPw = ref(false)

const numBoardShow = ref(false)
const showCalendar = ref(false)
const showTime = ref(false)
const showDuration = ref(false)

const isEdit = computed(() => liveForm.id)

const isMine = ref(false)

const selectedUsers = ref([])

// 选择用户
const chooseUser = () => {
  wxContacts(selectedUsers.value, (list) => {
    selectedUsers.value = list
  })
}
// 移除用户
const delUser = (index) => {
  selectedUsers.value.splice(index, 1)
}

const sendMsg = async(data) => {
  // 未选择参会人员的话
  if (!selectedUsers.value.length) {
    return
  }
  const msg = {
    users: selectedUsers.value.map((item) => item.id),
    content: {
      title: data.title,
      description: `<div class=\"normal\">直播时间：${dayjs(data.startTime).format('YYYY-MM-DD HH:mm')}至${dayjs(data.endTime).format('YYYY-MM-DD HH:mm')}</div><br/><div class=\"normal\">直播号：${data.meetingRoomNumber}</div><br/><div class=\"normal\">密码：${sm2Decrypt(data.meetingPassword)}</div>`,
      url: `${WEB_HREF}/info?id=${data.id}`
    }
  }
  console.log('sendmsg >>>', msg)
  await sendMsgCard(msg)
}

// 保存
const submitForm = async() => {
  let msg = ''
  const startTime = `${liveForm.dateText} ${liveForm.time}:00`
  if (!liveForm.title) {
    msg = '请填写直播主题'
  } else if (!liveForm.speaker) {
    msg = '请输入此次直播的主讲人'
  } else if (liveForm.title.length > 40) {
    msg = '直播主题字数在40字以内'
  } else if (!liveForm.meetingPassword) {
    msg = '请填写直播密码'
  } else if (!/^\d{6}$/.test(liveForm.meetingPassword)) {
    msg = '请输入6位的数字密码'
  } else if (dayjs(startTime).toDate().getTime() - new Date().getTime() < 0) {
    msg = '请选择当前时间之后的时间'
  }
  if (msg) {
    VantMessage.warning(msg)
    return
  }
  const loading = showLoadingToast({
    message: '保存中...',
    forbidClick: true,
    duration: 0
  })
  // SM2 加密
  // let password = sm2Encrypt(liveForm.controlPassword)
  // password = sm2Decrypt(password)
  // console.log('password >>>', password)
  const data = {
    ...liveForm,
    durationTime: liveForm.durationTime[0],
    startTime,
    autoRecording: liveForm.autoRecording ? '1' : '0',
    autoPublishRecording: liveForm.autoRecording ? '1' : '0',
    meetingPassword: sm2Encrypt(liveForm.meetingPassword.toString()),
    controlPassword: sm2Encrypt(liveForm.controlPassword.toString())
  }
  // 移除不必要的参数
  delete data.date
  delete data.pickerTime
  delete data.durationText
  delete data.dateText
  delete data.time
  delete data.elTimeDate

  if (!isEdit.value) {
    delete data.id
  }
  try {
    const res = await saveLive(data)
    console.log('save res >>>', res)
    loading.close()
    if (res && res.data) {
      VantMessage.success('保存成功')
      sendMsg(res.data)
      $router.go(-1)
    } else {
      VantMessage.error('保存失败')
    }
  } catch (error) {
    loading.close()
    VantMessage.error('保存失败')
  }
}

// 获取详情
const getLiveInfo = async(id) => {
  try {
    const res = await getInfo(id)
    if (res.data) {
      const info = res.data
      const state = info.liveState
      let msg = ''
      if (state === '1' || state === '2') {
        msg = '直播已开始'
      } else if (state === '3') {
        msg = '直播结束'
      }
      // 回退
      if (msg) {
        VantMessage.info(msg)
        $router.go(-1)
        return
      }

      // 设置详情
      liveForm.id = info.id
      liveForm.title = info.title
      liveForm.speaker = info.speaker || ''
      liveForm.autoRecording = info.autoRecording === '1'
      liveForm.date = dayjs(info.startTime).toDate()
      liveForm.pickerTime = dayjs(info.startTime).format('HH:mm').split(':')
      liveForm.durationTime = [info.durationTime]
      liveForm.meetingPassword = sm2Decrypt(info.meetingPassword)
      liveForm.controlPassword = info.controlPassword
        ? sm2Decrypt(info.controlPassword)
        : getControlPwd()
      liveForm.location = info.location
      liveForm.briefIntroduction = info.briefIntroduction
      liveForm.elTimeDate = dayjs(info.startTime).toDate()
      // 不是我的直播不能编辑
      isMine.value =
        process.env.NODE_ENV === 'development'
          ? false
          : authStore.userId === info.userId
    } else {
      // FIXME:直播不存在后，向后退
      VantMessage.error('直播不存在')
      $router.go(-1)
    }
  } catch (error) {
    VantMessage.error('获取直播详情失败')
  }
}

// 获取主持人密码
const getControlPwd = () => {
  return Array.from({ length: 6 }, (v, i) => getRandomInt(0, 10)).join('')
}
// 初始化
const initLiveForm = () => {
  //
  const query = $route.query
  if (query.id) {
    liveForm.id = query.id
    getLiveInfo(query.id)
  } else {
    const diff = 5 // 多少分钟以后
    const nextTime = new Date().getTime() + diff * 60 * 1000
    const nextDate = dayjs(nextTime).format('YYYY-MM-DD HH:mm').split(' ')
    liveForm.id = ''
    liveForm.date = new Date(nextTime)
    liveForm.dateText = nextDate[0]
    liveForm.time = nextDate[1]
    liveForm.pickerTime = nextDate[1].split(':')
    liveForm.elTimeDate = dayjs(nextTime).toDate()
    liveForm.controlPassword = getControlPwd()
  }
}

const onDateConfirm = (val) => {
  // console.log('val', dayjs('2023-11-22').toDate())
  liveForm.date = val
  showCalendar.value = false
}

const onTimeConfirm = ({ selectedValues }) => {
  const select = `${liveForm.dateText} ${selectedValues.join(':')}:00`
  const diff = dayjs(select).toDate().getTime() - new Date().getTime()
  // 选中的时间要大于等于当前的时间
  if (diff < 0) {
    // 选中不会的时间
    VantMessage.warning('请选择当前时间之后的时间')
    return
  }
  liveForm.pickerTime = selectedValues
  showTime.value = false
}

const onDurationConfirm = ({ selectedValues }) => {
  liveForm.durationTime = selectedValues
  showDuration.value = false
}

const disabledDate = (date) => {
  return date.getTime() < Date.now() - 8.64e7
}

// 初始化请求数据
initLiveForm()

watch(
  () => liveForm.date,
  (val) => {
    liveForm.dateText = dayjs(val).format('YYYY-MM-DD')
  }
)

watch(
  () => liveForm.pickerTime,
  (val) => {
    liveForm.time = val.join(':')
  }
)

watch(
  () => liveForm.elTimeDate,
  (val) => {
    liveForm.time = dayjs(val).format('HH:mm')
  }
)

watch(
  () => liveForm.durationTime,
  (val) => {
    liveForm.durationText = TIME_COLOBJ[val[0]]
  }
)
</script>

<style lang="less" scoped src="@/styles/add.less"></style>
